const express = require("express");
const router = express.Router();
const db = require("../models");
const crypt = require("../tools/crypt");
const verify = require("../tools/verifyToken");

router.get("/all", verify, (req, res) => {
  console.log(req.ip);
  db.Staff.findAll({ include: "department" })
    .then((staffs) => res.send(staffs))
    .catch((err) => {
      res.send(err);
    });
});

router.get("/:name", verify, (req, res) => {
  db.Staff.findAll({
    where: {
      staff_name: req.params.name,
    },
  })
    .then((staff) => {
      res.send(staff);
    })
    .catch((err) => {
      console.error(err);
    });
});

router.post("/add", verify, (req, res) => {
  let staff = req.body;

  const hashedPassword = crypt.encrypt(staff.password);
  staff.password = hashedPassword;
  console.log(staff);
  db.Staff.create(staff)
    .then((staff) => {
      res.send(staff);
    })
    .catch((err) => {
      console.error(err);
      res.send({ msg: "请输入正确的员工信息！" });
    });
});

router.post("/delete", verify, (req, res) => {
  console.log(req.body);
  db.Staff.destroy({
    where: {
      id: req.body.id,
    },
  })
    .then((result) => {
      res.send({ result: result });
    })
    .catch((err) => {
      res.send(err);
    });
});

router.post("/edit", verify, (req, res) => {
  db.Staff.update(req.body, {
    where: {
      id: req.body.id,
    },
  })
    .then((staff) => {
      res.send(staff);
    })
    .catch((err) => {
      console.error(err);
    });
});
router.put("/updatePasswd", verify, async (req, res) => {
  const user = req.body;
  if (user.password !== user.passwdRepeat) {
    res.status(400).send("两次密码不一致！");
    return;
  }
  const staff = await db.Staff.findOne({ where: { id: user.id } });
  if (!staff) {
    res.status(400).send({ msg: "无此用户！" });
    return;
  }
  console.log(staff);
  const passwdCorrect = crypt.correct(user.oldPasswd, staff.password);
  if (!passwdCorrect) {
    res.status(400).send({ msg: "原密码错误！" });
    return;
  }
  hashedPasswd = crypt.encrypt(user.password);
  db.Staff.update({ password: hashedPasswd }, { where: { id: user.id } })
    .then((updated) => {
      res.send({ updated: updated });
    })
    .catch((err) => {
      res.send({ err: err });
    });
});

router.put("/resetPasswd", verify, async (req, res) => {
  const id = req.body.id;
  if (!id) {
    res.status(400).send({ msg: "请输入正确的id" });
    return;
  }
  const staff = await db.Staff.findOne({ where: { id: id } });
  if (!staff) {
    res.status(400).send({ msg: "此用户不存在！" });
    return;
  }
  const password = crypt.encrypt("123456");
  db.Staff.update({ password: password }, { where: { id: id } })
    .then((updated) => {
      res.send({ updated: updated });
    })
    .catch((err) => {
      res.send({ err: err });
    });
});
module.exports = router;
